﻿using Ah.Testudin.Engine.Actors.Components.Animation;
using Ah.Testudin.Engine.Events;
using Microsoft.Xna.Framework;

namespace Ah.Testudin.Engine.Actors.Components
{
    public class PlayerComponent : IActorComponent
    {
        #region Properties

        public string Name { get; private set; }

        #endregion

        #region Constructors

        public PlayerComponent(
            Actor actor,
            string playerName)
        {
            this.Owner = actor;

            this.Name = playerName;

            EventManagerSingleton.Instance.RegisterEventHandler(
                EventType.MissileFired,
                HandleMissileFiredEvent);

            EventManagerSingleton.Instance.RegisterEventHandler(
                EventType.ActorDestroyed,
                HandleActorDestroyedEvent);
        }

        #endregion

        #region ActorComponentBase

        public void Update(GameTime gameTime)
        {
        }
        
        public Actor Owner { get; private set; }

        public void Dispose()
        {
        }

        #endregion

        #region Private Methods

        private void HandleMissileFiredEvent(ITestudinEvent testudinEvent)
        {
            MissileFiredEvent missileFiredEvent = testudinEvent as MissileFiredEvent;

            if (missileFiredEvent.ActorId == this.Owner.Id)
            {
                this.Owner.SetComponent<IAnimationComponent>(
                    new FireMissileAnimationComponent(
                        this.Owner,
                        EventManagerSingleton.Instance));
            }
        }

        private void HandleActorDestroyedEvent(ITestudinEvent testudinEvent)
        {
            ActorDestroyedEvent actorDestroyedEvent = testudinEvent as ActorDestroyedEvent;

            if (actorDestroyedEvent.ActorId == this.Owner.Id)
            {
                EventManagerSingleton.Instance.QueueEvent(
                    new PlayerDiedEvent(
                        this.Owner.Id));
            }
        }

        #endregion
    }
}
